<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

	<xsl:template match="HeaderInfo">
        
#define XMLIGNOREVALUES
#undef EMAIL_LOG
#undef AUDIT

using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Diagnostics;

using System.Net;
using System.Net.Mail;
using System.Net.Mime;


#if(AJAX)
using AjaxStub;
#endif

#if(AJAXPRO)
using AjaxPro;
#endif


namespace <xsl:value-of select="ProjectName"/>.DataObject {

	[Serializable]
	public abstract class <xsl:value-of select="ProjectName"/>DOS {
		protected Guid objectID = Guid.Empty;
		protected DateTime createdDate;
		protected DateTime modifiedDate;
		
		public Guid ObjectID { get { return objectID; } set { objectID = value; } }
		public DateTime ModifiedDate { get { return modifiedDate; } set { modifiedDate=value; } }
		public DateTime CreatedDate { get { return createdDate; } set { createdDate=value; } }
	}

	public class EnumSelection {
	
		private string name;
		private int @value;
		
		public string Name { get { return name; } set { name = value; } }
		public int Value { get { return @value; } set { @value = value; } }
		
		public EnumSelection ( string _name, int _value )
		{
			Name = _name;
			Value = _value;
		}
	}




	[Serializable]
	public abstract class <xsl:value-of select="ProjectName"/>DataObject {
	
		protected Guid objectID=Guid.Empty;
		protected DateTime createdDate;
		protected DateTime modifiedDate;
		
		
		#if(XMLIGNOREVALUES)
		[XmlIgnore]
		#endif		
		// WARNING: This flag is not modified on array list modifications
			public bool dirty=false;
		
		// this flag will not be modified unless
		// we do a SaveNoDupe() call.
		public bool isDupe=false;
			
		
		// Must have an auditLog class in the system for this to work
		public void writeAudit ( ModType mt )
		{

			// Don't audit the audit!
			if ( this.GetType().Name.Equals ( "AuditLog" ) ) return;

			
			System.Text.StringBuilder auditData = new System.Text.StringBuilder ();
			
			foreach ( PropertyInfo pt in this.GetType().GetProperties() )
			{
				auditData.Append ( pt.Name + ": " + pt.GetValue ( this , 
					new object[0] ).ToString().Replace ( ";","\\;" )  + ";" );
			}
			
			
			AuditLog auditLog =new AuditLog ();
			auditLog.Modification = mt;			
			auditLog.Data = auditData.ToString ();
			auditLog.Name = this.GetType().Name;
			auditLog.UserName = System.Threading.Thread.CurrentPrincipal.Identity.Name;
			#if(AUDIT)
			auditLog.Save ();
			#endif
			
		
		}
			
		
		#if(XMLIGNOREVALUES)
		[XmlIgnore]
		#endif
		public bool forceNew=false;
		
		
		
		[System.Xml.Serialization.XmlIgnore()]
		public int timezoneOffset = 0;
			
		public Guid ObjectID { get { return objectID; } set { objectID=value; } }
		
		#if(XMLIGNOREVALUES)
		[XmlIgnore]
		#endif
		public DateTime CreatedDate { get { return createdDate; } set { createdDate=value; } }

		#if(XMLIGNOREVALUES)
		[XmlIgnore]
		#endif
		public DateTime ModifiedDate { get { return modifiedDate; } set { modifiedDate=value; } }
		

		public string CreatedDate_Nice { get { return createdDate.ToString("dd-MMM-yy HH:mm"); } set { } }
		public string ModifiedDate_Nice { get { return modifiedDate.ToString("dd-MMM-yy HH:mm"); } set { } }
		
		public Int64 CreatedDate_Ticks { get { return createdDate.Ticks; } set {} }
		public Int64 ModifiedDate_Ticks { get { return modifiedDate.Ticks; } set {} }
		
				
		
		public <xsl:value-of select="ProjectName"/>DataObject(Guid ID) {
			this.Load(ID);
		}
		
		// default constructor
		public <xsl:value-of select="ProjectName"/>DataObject() {}
        
		public <xsl:value-of select="ProjectName"/>DataObject ( int timezoneOffset ) {
		    this.timezoneOffset = timezoneOffset;
		}
		
		
		// Only saves the object if there is no other object with a tostring
		// of the same value.
		public virtual bool SaveNoDupe() {
		    // TODO: Check the 'tostring' value of an
		    // object for anything with a matching name
		    // if something is found assume this is the
		    // duplicate and wham! no save.
		    
		    Guid[] matches=this.Get_ToString(this.ToString());
		    
		    if(matches.Length>1) {
			isDupe=true;
			return false;
		    }
		    
		    foreach(Guid id in matches) {
			if(id!=this.ObjectID) {
			    isDupe=true;
			    return false;                
			}
		    }
		    
		    return Save();
		}
		
		protected abstract bool isLatest ( SqlConnection sqlCon );
		
		// Provides first commit wins concurrency
		public virtual bool SaveFirstCommitWins ( bool throwsException )
		{
			bool ret = false;
			try 
			{
				using(SqlConnection sqlCon=new SqlConnection(GetDB())) {
					sqlCon.Open();
			
					if ( ! isLatest ( sqlCon ) ) 
					{
						throw new StaleObjectException ( "<xsl:value-of select="Name"/> " );
						return false;
					}
					ret = insertOrUpdate ( sqlCon );
					
					sqlCon.Close();
				}
			}
			catch(Exception ex) {
				ReportException(ex); return false;
			}
			return ret;
		
		}
		
		public class StaleObjectException : Exception 
		{
			string message;
			
			public override string Message { get { return message; } }
		
			public StaleObjectException ( string message )
			{
				this.message = message;
			}
		
		}
		
		
		protected bool insertOrUpdate ( SqlConnection sqlCon )
		{
			return insertOrUpdate ( sqlCon , false );
		}
		
		protected bool insertOrUpdate ( SqlConnection sqlCon , bool auditLog )
		{
			if(objectID==Guid.Empty || forceNew) 
			{
				if ( objectID == Guid.Empty )
				{
					objectID=Guid.NewGuid();
				}
				
				return insert ( sqlCon );
				
			} else {
				if ( auditLog ) {
				
					// need to load the object again
					
					LoadSingle ( ObjectID ).insert ( sqlCon , true );
					
					//insert ( sqlCon , true ); // do the audit
				
				
				}
				return update ( sqlCon );
			}
		}
		
		
		
				
		public static object ScalerQuery ( string query )
		{
			object result = null;
			try
			{
				using( SqlConnection sqlCon=new SqlConnection( GetDB () ) ) {
					sqlCon.Open ();
					using ( SqlCommand sqlCom = new SqlCommand ( query , sqlCon ) )
					{
						result = sqlCom.ExecuteScalar ();
					}
					sqlCon.Close ();
				}
			
			}
			catch ( Exception ex )
			{
				<xsl:value-of select="ProjectName"/>DataObject.ReportException ( ex );
			}
			
			return result;		
		}
		
		
		public virtual bool SaveAudit ()
		{
			return Save ( true );
		}
		
		public virtual bool Save () { return Save ( false ); }
		
		public virtual bool Save( bool auditLog ) 
		{
			bool ret = false;
			if(!dirty &#38;&#38; objectID != Guid.Empty) 
			{
				return true;
			}
			
			try 
			{
				using ( SqlConnection sqlCon = new SqlConnection ( GetDB () ) ) 
				{
					sqlCon.Open ();
					ret = insertOrUpdate ( sqlCon , auditLog );
					sqlCon.Close ();
				}
			} 
			catch ( Exception ex ) 
			{
				ReportException ( ex ); 
				return false;
			}
			return ret;
		}
		
		protected abstract bool insert(SqlConnection sqlCon);
		protected abstract bool insert(SqlConnection sqlCon, bool isAudit);
		protected abstract bool update(SqlConnection sqlCon);
		
		public abstract <xsl:value-of select="ProjectName"/>DataObject LoadSingle ( Guid id );
        
		protected abstract Guid[] Get_ToString(object val);

		public abstract bool delete();
		
		public bool Load ( Guid ID ) { return Load ( ID , false ); }
		public abstract bool Load( Guid ID , bool audit );
		
		
		
		
		
		// gets the database connection
		public static string GetDB() {
			if(System.Configuration.ConfigurationSettings.AppSettings["DB"]==null) {
				return "<xsl:value-of select="DBConnection"/>";
			}
			return System.Configuration.ConfigurationSettings.AppSettings["DB"];
		}
		
		protected void setDefaults(<xsl:value-of select="ProjectName"/>DataObject obj, SqlDataReader sqlDr) {
			obj.createdDate=(DateTime)sqlDr["Created"];
			obj.modifiedDate=(DateTime)sqlDr["Modified"];
		}
		
		
		
		
		const string EVENT_LOG_SOURCE="<xsl:value-of select="ProjectName"/>";


		/*
		To create the event log source for ASP.NET application do the following
		
		* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application
		* Right-click the Application subkey, point to New, and then click Key
		* Name it <xsl:value-of select="ProjectName"/>
		
		From
		http://support.microsoft.com/default.aspx?scid=kb;en-us;329291
		
		*/
		public static void ReportException(Exception ex) {
				
			#if ( EVENT_LOG )
			if(!EventLog.SourceExists(EVENT_LOG_SOURCE)) 
			{
				EventLog.CreateEventSource(EVENT_LOG_SOURCE,"Application");
			}
		
			using(EventLog eventLog=new EventLog("Application")) 
			{
				eventLog.Source=EVENT_LOG_SOURCE;

				eventLog.WriteEntry(ex.Message + " " + ex.StackTrace + " " + 
					ex.InnerException + " " + ex.Source + " " + ex.GetBaseException().Message,
					EventLogEntryType.Error);

			}
			
			#endif
			
			#if ( WINDOW_LOG )
			
			System.Diagnostics.Debug.Assert ( false , "<xsl:value-of select="ProjectName"/> DO Exception" , ex.Message + " " + ex.StackTrace + " " + 
					ex.InnerException + " " + ex.Source + " " + ex.GetBaseException().Message);
			
			#endif
			
			
			#if ( EMAIL_LOG) 
			
			string smtpServer = "localhost";
			string _to = "gbrewer+<xsl:value-of select="ProjectName"/>+EXCEPTION@gmail.com";
			string _from = "codegen@g33.org";
			
			if(System.Configuration.ConfigurationSettings.AppSettings["SMTP_SERVER"]!=null) {
				smtpServer = System.Configuration.ConfigurationSettings.AppSettings["SMTP_SERVER"];











			}
			
			if(System.Configuration.ConfigurationSettings.AppSettings["SMTP_LOG_TO"]!=null) {
				_to = System.Configuration.ConfigurationSettings.AppSettings["SMTP_LOG_TO"];
			}
			
			if(System.Configuration.ConfigurationSettings.AppSettings["SMTP_LOG_FROM"]!=null) {
				_from = System.Configuration.ConfigurationSettings.AppSettings["SMTP_LOG_FROM"];
			}

#if ( ! DEBUG )
			SmtpClient client = new SmtpClient ( smtpServer );
			
			MailMessage mailMessage = new MailMessage ( _from , _to , 
			"<xsl:value-of select="ProjectName"/> Exception", ex.Message + " " + ex.StackTrace + " " + 
					ex.InnerException + " " + ex.Source + " " + ex.GetBaseException().Message );
			
			
			client.Send ( mailMessage );
			
#endif			
			
			#endif		
			

		}
    

		#if(AJAX || AJAXPRO)

		// These are some generic ajax controls that can be used to perform 
		// data operations on objects
		[Serializable()]
		#if(AJAXPRO)
		[AjaxPro.AjaxNamespace("GenericAJAXControls")]
		#endif
		public class GenericAJAXControls {

			[AjaxMethod()]
			public bool DeleteObj(string type, Guid id) {
				object o=typeof(<xsl:value-of select="ProjectName"/>DataObject).Assembly.GetType("<xsl:value-of select="ProjectName"/>." + 
				type,false,true).GetConstructor(new Type[]{typeof(Guid)}).Invoke(
				new object[]{id});
				return (bool)(o.GetType().GetMethod("delete", new Type[0]).Invoke(o, new object[0]));
			}

		}
    
		#endif
		
	}

}

	
	
	</xsl:template>
</xsl:stylesheet>

  